import React, { useState } from "react"
import { LeftOutline } from "antd-mobile-icons"
import "./index.scss"
import { SearchBar } from "antd-mobile"
import { useHistory } from "react-router-dom"
import { DeleteOutline, CloseOutline } from "antd-mobile-icons"
function Search() {
  const history = useHistory()
  // 搜索关键字
  const [inputValue, setInputValue] = useState("")
  // // 搜索结果
  // const [searchResult, setSearchResult] = useState()
  // 搜索历史
  const [searchHistory, setSearchHistory] = useState(
    JSON.parse(localStorage.getItem("history")) || []
  )
  // 搜索
  const handleSearch = async () => {
    if (inputValue === "") return
    // 将搜索内容保存
    setSearchHistory(searchHistory.push(inputValue))
    localStorage.setItem("history", JSON.stringify(searchHistory))
    // 跳转搜索结果页面
    history.push("/searchResult", inputValue)
    console.log(searchHistory)
  }
  // 删除单个搜索记录
  const delHistory = (e, i) => {
    e.stopPropagation()
    const newHistory = searchHistory.filter((item, index) => index !== i)
    setSearchHistory(newHistory)
    localStorage.setItem("history", JSON.stringify(newHistory))
  }
  return (
    <div>
      <div className="search-title">
        <span className="search-back" onClick={() => history.go(-1)}>
          <LeftOutline />
        </span>
        <SearchBar
          style={{
            "--border-radius": "100px",
            "--placeholder-color": "#d1d1d1"
          }}
          className="searchInput"
          placeholder="请输入搜索关键词"
          value={inputValue}
          onChange={(value) => {
            setInputValue(value)
          }}
        />
        <span className="search-btn" onClick={handleSearch}>
          搜索
        </span>
      </div>
      <div className="search-history">
        <div className="history-title">
          <span>历史记录</span>
          <DeleteOutline className="deleteIcon" />
        </div>
        <div className="history-list">
          {searchHistory.map((item, index) => {
            return (
              <div
                key={index}
                className="history-item"
                onClick={() => {
                  history.push("/searchResult", item)
                }}
              >
                <span>{item}</span>
                <CloseOutline
                  className="delItem"
                  onClick={(e) => delHistory(e, index)}
                />
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
}

export default Search
